package com.xxx.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxx.common.Result;
import com.xxx.converter.MattersConverter;
import com.xxx.dto.MattersDto;

import com.xxx.dto.RangeWarningDto;
import com.xxx.pojo.*;
import com.xxx.reportingsystem.service.UserService;
import com.xxx.service.*;
import com.xxx.utils.ExportUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RestController
@RequestMapping("/matters")
@Slf4j
public class MatterController {

    @Autowired
    private MattersService mattersService;

    @Autowired
    private RangeWarningService rangeWarningService;

    @Autowired
    private UserService userService;

    @Autowired
    private AlgorithmService algorithmService;

    @Autowired
    private AuditInfoService auditInfoService;

    @GetMapping("/test")
    public String test() {
        return "测试内容";
    }

    @PreAuthorize("hasAnyAuthority('sys:add:matter')")
    @PostMapping("/save-matters")
    public Result saveMatters(@RequestBody Matters matters) {
        log.info("mattersDto:{}", matters);

        //日期转换id
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String format = "XM" + now.format(formatter);

        Matters one = mattersService.getOne(new LambdaUpdateWrapper<Matters>()
                .like(Matters::getId, format)
                .orderByDesc(Matters::getId).last("limit 1"));

        //id自增
        if (one == null) {
            format = format + "0001";
        } else {
            String id = one.getId();
            String substring = id.substring(id.length() - 4, id.length());
            Integer integer = Integer.valueOf(substring) + 1;
            //将数字转化为4位字符串
            format = format + String.format("%04d", integer);
        }
        log.info("format:{}", format);

        LoginUser principal = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        matters.setUserId(principal.getUser().getUserId().longValue());

        //保存
        boolean save = mattersService.save(matters);

        return save ? Result.success("保存成功") : Result.error("保存失败");
    }


    //修改（审核）

    @Transactional
    @PutMapping("/up-matters")
    public Result updateMatters(@RequestBody AuditInfo auditInfo){
        log.info("auditInfo:{}",auditInfo);
        //实例化matters

        Matters matters = new Matters();
        matters.setId(auditInfo.getMattersId());
        matters.setStatus(auditInfo.getStatus());

        if (!auditInfoService.save(auditInfo) || !mattersService.updateById(matters)){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("保存错误");
        }

        return Result.success("保存成功");
    }

    //查询项目
    @PostMapping("/get-matters")
    @PreAuthorize("hasAuthority('sys:select:matter')")
    public Result getMatters(@RequestBody Matters matters, String name, Integer pageNo, Integer pageSize) {
        log.info("matters:{},\n pageNo:{},\npageSize:{}", matters, pageNo, pageSize);

        IPage iPage = new Page(pageNo, pageSize);

        List<User> userList = null;
        Set<Long> set = null;
        //模糊查询用户名
        if (name != null) {
            userList = userService.list(new LambdaQueryWrapper<User>().like(User::getName, name));
            set = userList.stream().map(user -> {
                Long value = user.getUserId().longValue();
                return value;
            }).collect(Collectors.toSet());
        }
        //查找相关数据
        iPage = mattersService.page(iPage, new LambdaQueryWrapper<Matters>()
                .like(matters.getName() != null, Matters::getName, matters.getName())
                .like(matters.getId() != null, Matters::getId, matters.getId())
                .like(matters.getDepartment() != null, Matters::getDepartment, matters.getDepartment())
                .like(matters.getReportingCategory() != null, Matters::getReportingCategory, matters.getReportingCategory())
                .like(matters.getUpdateDatetime() != null, Matters::getUpdateDatetime, matters.getUpdateDatetime())
                .in(name != null, Matters::getUserId, set));

        //提取数据的报备人id
        List<Matters> records = iPage.getRecords();
        set = records.stream().map(o -> o.getUserId()).collect(Collectors.toSet());

        log.info("set:{}", set);

        //查询报备人的相关信息
        List<User> users = userService.listByIds(set);

        //传入到mattersDto数据
        List<MattersDto> mattersDtoList = records.stream().map(o -> {
            MattersDto mattersDto = new MattersDto();

            //复制成员变量
            BeanUtils.copyProperties(o, mattersDto);
            users.stream().map(user -> {
                if (o.getUserId().equals(user.getUserId().longValue())) {
                    mattersDto.setUser(user);
                }
                return mattersDto;
            });

            AuditInfo auditInfo = auditInfoService.getById(mattersDto.getId());
            List<Integer> integerList = Stream.of(o.getClassification().split(","))
                    .map(s -> Integer.valueOf(s)).collect(Collectors.toList());
            mattersDto.setAuditInfo(auditInfo);
            //查询预警范围
            List<RangeWarning> warningList = rangeWarningService.listByIds(integerList);

            List<RangeWarningDto> warningDtoList = warningList.stream().map(rangeWarning -> {
                RangeWarningDto rangeWarningDto = new RangeWarningDto();
                BeanUtils.copyProperties(rangeWarning, rangeWarningDto);

                if (rangeWarning.getAlgorithm() != null) {
                    Algorithm algorithm = algorithmService.getById(rangeWarning.getAlgorithm());
                    rangeWarningDto.setAlgorithmInfo(algorithm);
                }
                return rangeWarningDto;
            }).collect(Collectors.toList());

            mattersDto.setWarningDtoList(warningDtoList);

            return mattersDto;
        }).collect(Collectors.toList());

        iPage.setRecords(mattersDtoList);

        return Result.success("成功", iPage);
    }



    @GetMapping("/export")
    @PreAuthorize("hasAnyAuthority('sys:add:matter')")
    public void exportUserExcel(HttpServletResponse response) {
        try {
            ExportUtil.setExcelResponseProp(response, "重大事项备案统计");
            List<Matters> mattersList = mattersService.list();
            for (Matters statistics : mattersList) {
                String[] split = statistics.getClassification().split(",");
                String s = split[0];
                RangeWarning byId = rangeWarningService.getById(s);
                statistics.setClassification(byId.getClassification());
            }
            EasyExcel.write(response.getOutputStream())
                    .head(Matters.class)
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet("重大事项备案统计")
                    .doWrite(mattersList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
